package reduce.fz.com.reduce.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.List;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.Video;
import reduce.fz.com.reduce.bean.VideoCard;
import reduce.fz.com.reduce.custom.LeftMenuItem;
import reduce.fz.com.reduce.custom.MaterialDialog;
import reduce.fz.com.reduce.custom.MaterialDialogBuilder;
import reduce.fz.com.reduce.custom.TabIndicator;
import reduce.fz.com.reduce.custom.view.RoundNetworkImageView;
import reduce.fz.com.reduce.fragment.DiscoverFragment;
import reduce.fz.com.reduce.fragment.FindTeamFragment;
import reduce.fz.com.reduce.fragment.FindVideoFragment;
import reduce.fz.com.reduce.fragment.FragmentCacheSupport;
import reduce.fz.com.reduce.fragment.HomeDynamicListFragment;
import reduce.fz.com.reduce.fragment.HotPkGroupFragment;
import reduce.fz.com.reduce.fragment.MySocietyFragment;
import reduce.fz.com.reduce.fragment.TeamCategoryFragment;
import reduce.fz.com.reduce.fragment.UserDetailFragment;
import reduce.fz.com.reduce.fragment.UserDetailFragment2;
import reduce.fz.com.reduce.service.preference.UserPreference;
import reduce.fz.com.reduce.util.ExitApp;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.QuPaiOper;
import reduce.fz.com.reduce.util.SetUtil;
import reduce.fz.com.reduce.util.ToastUtil;
import reduce.fz.com.reduce.util.photo.PhotoSelect;
import reduce.fz.com.reduce.util.photo.SelectParam;

/**
 * 左边抽屉式主页面(首页)
 */
public class DoorActivity extends BaseToolBarActivity implements View.OnClickListener {

    private Fragment mCurrentFragment;
    private FragmentManager mFragmentManager;
    private MaterialDialog targetDialog;
    private QuPaiOper quPaiOper;
    private Video video = null;

    //秀场
    private RadioButton mSHow;
    //发起
    private RadioButton mPub;
    //录像
    private ImageView mRecord;
    //社团
    private RadioButton mSociety;
    //我的
    private RadioButton mMe;

    /**
     * 发起PK挑战
     */
    private static final int REQUEST_CODE_PK = 1113;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case QuPaiOper.RECORDE_SHOW:
                if (data == null) return;
                video = quPaiOper.dealIntent(data);
                forwardEdit(video);
                break;
            case REQUEST_CODE_PK:
                if (data == null) return;
                video = quPaiOper.dealIntent(data);
                forwardPkCreate(video);
            default:
                break;
        }
    }

    /**
     * 进入视频编辑页面
     *
     * @param video
     */
    public void forwardEdit(Video video) {
        VideoCard card = new VideoCard();
        card.video = video;
        Intent intent = new Intent(DoorActivity.this, VideoEditDescActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("videocard", card);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void forwardPkCreate(Video video) {
        VideoCard card = new VideoCard();
        card.video = video;
        Intent intent = new Intent(DoorActivity.this, PkGroupCreateActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("videocard", card);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    //左侧菜单组件
    //我的小组
    private LeftMenuItem menuHome;
    private LeftMenuItem menuShow;
    private LeftMenuItem menuPk;

    //发表意见
    private LeftMenuItem menuSuggestion;
    //我的
    private LeftMenuItem menuMe;
    //用户头像
    private RoundNetworkImageView mIvUserHeader;
    //昵称
    private TextView mTvNickName;

    private ImageView mSex;
    //收藏
    private TextView mTvCollect;
    //消息
    private TextView mTvMessage;
    //设置
    private TextView mTvSetting;
    //退出
    private TextView mLoginOut;

    private TextView rightButton;


    public void initWidget() {
        mSHow = (RadioButton) findViewById(R.id.radio_show);
        mPub = (RadioButton) findViewById(R.id.radio_pub);
        mRecord = (ImageView) findViewById(R.id.iv_record);
        mSociety = (RadioButton) findViewById(R.id.radio_society);
        mMe = (RadioButton) findViewById(R.id.radio_me);

        mSHow.setOnClickListener(this);
        mPub.setOnClickListener(this);
        mRecord.setOnClickListener(this);
        mSociety.setOnClickListener(this);
        mMe.setOnClickListener(this);


        menuHome = (LeftMenuItem) findViewById(R.id.menu_home);
        menuShow = (LeftMenuItem) findViewById(R.id.menu_show);
        menuPk = (LeftMenuItem) findViewById(R.id.menu_pk);
        menuSuggestion = (LeftMenuItem) findViewById(R.id.menu_suggestion);
        menuMe = (LeftMenuItem) findViewById(R.id.menu_me);
       /* mIvUserHeader = (RoundNetworkImageView) findViewById(R.id.iv_user_header);
        mTvNickName = (TextView) findViewById(R.id.tv_user_nickname);
        mSex = (ImageView) findViewById(R.id.iv_sex);
        mTvCollect = (TextView) findViewById(R.id.tv_collect);
        mTvMessage = (TextView) findViewById(R.id.tv_message);
        mTvSetting = (TextView) findViewById(R.id.tv_setting);
        mLoginOut = (TextView) findViewById(R.id.tv_login_out);

        menuSuggestion.setOnClickListener(this);
        menuHome.setOnClickListener(this);
        menuShow.setOnClickListener(this);
        menuPk.setOnClickListener(this);
        menuMe.setOnClickListener(this);
        mTvCollect.setOnClickListener(this);
        mTvMessage.setOnClickListener(this);
        mTvSetting.setOnClickListener(this);
        mLoginOut.setOnClickListener(this);*/
    }


    public void initInfo() {
        User user = UserPreference.getUser();
        mIvUserHeader.setImageUrl(user.avatar, HttpUtils.getAvatarImageLoader());
        mTvNickName.setText(user.nickname);
        mSex.setImageResource("M".equals(user.sex) ? R.drawable.icon_boy : R.drawable.icon_gril);
    }

    public void displayFirstFragment() {
        setShowTab();
    }

    /**
     * 显示fragment(通过attach和detach避免重复创建)
     *
     * @param fragment
     * @param cacheKey
     */
    public void showFragment(Fragment fragment, String cacheKey, Boolean showTitle) {
        displayRightBtn(false);
        android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        //先确认如果和当前的fragment相同，则不做处理
        if (mCurrentFragment != null && mCurrentFragment == fragment) return;
        //从缓存中获取fragment
        Fragment cacheFragment = getFragmentByContext(cacheKey);
        if (mCurrentFragment != null)
            fragmentTransaction.detach(mCurrentFragment);
        if (cacheFragment != null && 1 != 1) {
            mCurrentFragment = cacheFragment;
            fragmentTransaction.attach(cacheFragment).commit();
        } else {
            mCurrentFragment = fragment;
            fragmentTransaction.add(R.id.main_content, fragment, cacheKey).commit();
        }
        if (showTitle)
            setToolbarTitle(((FragmentCacheSupport) fragment).getFragmentTitle());
    }

    public String getCacheKey(int position, String prefix) {
        return prefix + "_" + position;
    }

    public Fragment getFragmentByContext(String name) {
        Fragment fragment = mFragmentManager.findFragmentByTag(name);
        return fragment;
    }

    private Long exitTime = 0L;
    private Long gap = 2000L;
    private SlidingMenu sm;
    private List<String> teamTitles;
    private TabIndicator.OnTabSelectedListener teamSelectListener;
    private List<String> showTitles;
    private TabIndicator.OnTabSelectedListener showSelectListener;
    private List<String> pkTitles;
    private TabIndicator.OnTabSelectedListener pkSelectListener;

    public void initShowTab() {

        String[] temp = getResources().getStringArray(R.array.tab_show_title);
        showTitles = SetUtil.toList(temp);
        showSelectListener = new TabIndicator.OnTabSelectedListener() {
            @Override
            public void onTabReselected(int position) {
            }

            @Override
            public void onTabSelected(int position) {
                showFragment(FindVideoFragment.create(position), TeamCategoryFragment.class.toString() + position, false);
            }
        };
    }

    public void initPkTab() {
        String[] temp = getResources().getStringArray(R.array.tab_pk_group_title);
        pkTitles = SetUtil.toList(temp);
        pkSelectListener = new TabIndicator.OnTabSelectedListener() {
            @Override
            public void onTabReselected(int position) {

            }

            @Override
            public void onTabSelected(int position) {
                switch (position) {
                    case 0:
                        showFragment(HotPkGroupFragment.createGroupFragment(), HotPkGroupFragment.class.toString() + position, false);
                        break;
                    case 1:
                        showFragment(HotPkGroupFragment.createHotGroupFragment(), HotPkGroupFragment.class.toString() + position, false);
                        break;
                    default:
                        break;
                }

            }
        };
    }


    public void showMeFragment() {
        User user = UserPreference.getUser();
        UserDetailFragment2 fragment = UserDetailFragment2.create(user.uid);
        showFragment(fragment, UserDetailFragment2.class.toString(), true);
    }


    //初始化
    public void initTeamTab() {
        String[] temp = getResources().getStringArray(R.array.tab_find_title);
        teamTitles = SetUtil.toList(temp);
        teamSelectListener = new TabIndicator.OnTabSelectedListener() {
            @Override
            public void onTabReselected(int position) {

            }

            @Override
            public void onTabSelected(int position) {
                switch (position) {
                    case 0:
                        showFragment(TeamCategoryFragment.create(), TeamCategoryFragment.class.toString(), false);
                        break;
                    case 1:
                        showFragment(FindTeamFragment.hotCreate(), FindTeamFragment.class.toString() + position, false);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    /**
     *
     */
    public void setTeamTab() {
        if (teamTitles == null) {
            initTeamTab();

        }
        setTabBar(teamTitles, teamSelectListener);
        showFragment(TeamCategoryFragment.create(), TeamCategoryFragment.class.toString(), false);
        setTabBarPositon(0);
    }

    /**
     * 设置广场秀
     */
    public void setShowTab() {
        if (showTitles == null) {
            initShowTab();
        }
        setTabBar(showTitles, showSelectListener);
        showFragment(FindVideoFragment.create(0), FindVideoFragment.class.toString(), false);
        setTabBarPositon(0);

    }

    /**
     * 设置pk秀
     */
    public void setPkTab() {
        if (pkTitles == null) {
            initPkTab();
        }
        //setToolbarTitle("PK场");
        setRightBtn(R.drawable.pk_create).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createPk();
            }
        });
        setTabBar(pkTitles, pkSelectListener);
        showFragment(HotPkGroupFragment.createGroupFragment(), HotPkGroupFragment.class.toString() + "0", false);
        setTabBarPositon(0);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.menu_home:
                showFragment(HomeDynamicListFragment.create(), HomeDynamicListFragment.class.toString(), true);
                break;
            case R.id.menu_show:
            case R.id.radio_show:
                setShowTab();
                setShowRightBtn();
                break;
            case R.id.menu_pk:
            case R.id.radio_pub:
                showFragment(DiscoverFragment.create(), DiscoverFragment.class.toString(), true);
               // setPkTab();
                break;
            case R.id.radio_society:
                showFragment(MySocietyFragment.create(), MySocietyFragment.class.toString(), true);
                break;
            case R.id.iv_record:
                luxiang();
                break;
            case R.id.radio_me:
                showMeFragment();
                break;
            case R.id.menu_suggestion:
                pressBar();
                suggestion();
                break;
            case R.id.tv_login_out:
                loginOut();
                break;
            case R.id.tv_collect:
                ToastUtil.showMessage(getResources().getString(R.string.not_support_now));
                break;
            case R.id.tv_message:
                ToastUtil.showMessage(getResources().getString(R.string.not_support_now));
                break;
            case R.id.tv_setting:
                ToastUtil.showMessage(getResources().getString(R.string.not_support_now));
                break;
        }
    }


    public void targetDiaglog() {
        if (targetDialog != null && targetDialog.isShowing()) return;
        targetDialog = MaterialDialogBuilder.getBuilder(this).content(R.string.target_setting).positiveText(R.string.target_create).negativeText(R.string.target_cancel).callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog dialog) {
                super.onPositive(dialog);

            }

            @Override
            public void onNeutral(MaterialDialog dialogInterface) {
                super.onNeutral(dialogInterface);
                targetDialog.dismiss();
            }
        }).build();
    }


    public void suggestion() {
        Intent intent = new Intent(DoorActivity.this, SuggestionActivity.class);
        startActivity(intent);
    }


    public void pubStory() {
        SelectParam selectParam = new SelectParam();
        selectParam.selectMax = 10;
        selectParam.nextActivity = PubShareStoryActivity.class.getName();
        PhotoSelect select = PhotoSelect.instance(DoorActivity.this, selectParam);
        select.selectPhoto();
    }

    @Override
    public void initListener() {

    }

    public void luxiang() {
        quPaiOper.showRecordPage();

    }

    /**
     * 发起挑战
     */
    public void createPk() {
        quPaiOper.showRecordPage(REQUEST_CODE_PK);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        //自定义左侧图标
        // customIcon = R.drawable.icon_toolbar_selector;
        super.onCreate(savedInstanceState);
        quPaiOper = QuPaiOper.instance(this, false);
       /* barLeftBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressBar();
            }
        });*/
        setContentView(R.layout.activity_door);
        mFragmentManager = getSupportFragmentManager();
        //设置菜单页
        /*sm = new SlidingMenu(this);
        sm.setMode(SlidingMenu.LEFT);
        sm.setShadowWidth(5);
        sm.setBehindOffsetRes(R.dimen.abc_action_bar1);
        sm.setShadowDrawable(R.color.gray);
        sm.setFadeDegree(0.35f);*/
        //设置slding menu的几种手势模式
        //TOUCHMODE_FULLSCREEN 全屏模式，在content页面中，滑动，可以打开sliding menu
        //TOUCHMODE_MARGIN 边缘模式，在content页面中，如果想打开slding ,你需要在屏幕边缘滑动才可以打开slding menu
        //TOUCHMODE_NONE 自然是不能通过手势打开啦
        /*sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        sm.setMenu(R.layout.layout_left_menu);
        sm.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);*/
        initWidget();
        //initInfo();
        //显示第一个fragment
        displayFirstFragment();

    }

    @Override
    protected void displayLeftBtn() {


    }

    public void setShowRightBtn() {
        rightButton = setRightBtn(R.drawable.take_video_shape);
        //录像按钮
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                luxiang();

            }
        });
    }


    /**
     * 退出
     */
    public void loginOut() {
        UserPreference.delUser();
        ExitApp.exit(this);
    }


    @Override
    public void pressBar() {
        sm.toggle(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                sm.toggle(true);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > gap) {
                Toast.makeText(getApplicationContext(), R.string.again_to_quit, Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                ExitApp.exit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
